// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.action) {
    case 'operation_hospital_info': {
      return operation_hospital_info(event, wxContext.OPENID)
    }
    case 'get_hospital_list': {
      return get_hospital_list(event, wxContext.OPENID)
    }
    case 'get_hospital_by_id': {
      return get_hospital_by_id(event)
    }
  }
}

/**
 * 获取需要受捐医院列表
 * offset: 0 （分页起始值，下一次需要offset * limit）
 * limit: 10 (分页大小)
 * filter: {
 *  'hospital_name': '协和',
 * }
 * 模糊查询
 * "filter": {
   "hospital_name": {
      "$regex":".*协和",
      "$options": "i"
    }
  }
  排序
 * order_by: ['_id', 'desc'] //default
 */
async function get_hospital_list(event, open_id) {
  var offset = event.offset ? event.offset : 0;
  var limit = event.limit ? event.limit : 10;
  var filter = event.filter ? event.filter : {};
  var is_broadcast = event.is_broadcast != undefined ? event.is_broadcast : 0;
  if (is_broadcast == 1) {
    filter.user_id = open_id;
  }
  var order_by = event.order_by ? event.order_by : ['_id', 'desc'];
  try {
    return await db.collection('hospital')
      .where(filter)
      .orderBy(order_by[0], order_by[1])
      .skip(offset)
      .limit(limit)
      .get({
        success: res => {
          return res
        },
        fail: err => {
          console.log(err)
        }
      })
  } catch(e) {
    console.log(e)
  }
}

/**
 * 根据id获取医院详情
 * 
 * request: id
 */
async function get_hospital_by_id(event) {
  const id = event.id
  try {
    let donateList = await cloud.callFunction({
      name: 'donate',
      data: {
        'action': 'query_donated_materials',
        'offset': 0,
        'limit': 10,
        'in_transit': 1,
        'donate_hospital_id': id
      },
      success: res => {
        let list = [];
        res.data.forEach(donate => {
          list.push(donate.materials)
        })
        return list;
      },
      fail: err => {
        console.log(err)
      }
    })
    let result = await db.collection('hospital')
      .doc(id)
      .get({
        success: res => {
          res.data.donate = donateInfo.data.materials;
          return res
        },
        fail: err => {
          console.log(err)
        }
      })
    result.data.donate = donateList;
    return result;
  } catch(e) {
    console.log(e)
  }
}

/**
 * 添加医院详情(前端可能用不到暂时)
 */
async function operation_hospital_info(event, open_id) {
  let hospital_info = {
    /**
     * 医院名
     */
    'hospital_name': event.hospital_name,
    /**
     * 医院url
     */
    'hospital_url': event.hospital_url,
    /**
     * 医院电话
     */
    'hospital_phone': event.hospital_phone,
    /**
     * 医院联系人
     */
    'hospital_contact': event.hospital_contact,
    /**
     * 医院联系人手机
     */
    'hospital_mobile': event.hospital_mobile,
    /**
     * 医院地址
     */
    'hospital_address': event.hospital_address,
    /**
     * 医院公众号
     */
    'hospital_public': event.hospital_public,
    /**
     * 医院logo
     */
    'hospital_logo': event.hospital_logo,
    /**
     * 医院说明
     */
    'hospital_content': event.hospital_content,
    /**
     * 需要物资
      'hospital_need':[{
        'goods_name':'医用防护口罩',
        'stock':1000,
        'daily_usage':500,
        'standard':'GB 19083-2010'
      }],
     */
    'hospital_need':event.hospital_need,
    "updated_at": new Date(),
    'user_id': open_id
  }
  try {
    if(event._id) {
      return await db.collection('hospital')
        .where({
          '_id': event._id,
          'user_id': open_id
        })
        .update({
          data: hospital_info,
          success: res => {
            console.log("update success")
          },
          fail: err => {
            console.log("update error")
          }
        })
    } else {
      hospital_info.created_at = new Date()
      return await db.collection('hospital')
        .add({
          data: hospital_info,
          success: res => {
            console.log("insert success")
          },
          fail: err => {
            console.log("insert error")
          }
        })
    }
  } catch (e) {
    console.log(e)
  }
}